<?php namespace App\Services;

use App\Facades\Infra\RoomManager;
use App\Exceptions\DataBaseException;
use Auth;

class RoomService{
	/**
	 * 新建酒店房间
	 */
	public function hotelCreateRoom($data){
		try {
			\DB::beginTransaction();

			$room = RoomManager::createRoom($this->formatData($data));

			$room->qrcode = $this->generateQRCode($room->hotel_id,$room->id);

			$room->save();

			\DB::commit();

		} catch (Exception $e) {

			\DB::rollBack();

			throw new DataBaseException('数据库异常');
		}

	}

	public function getRooms($conditions){
		return RoomManager::getRooms($conditions,true)->orderBy('created_at','desc')->paginate(15);
	}

	public function getRoom($conditions){
		return RoomManager::getRooms($conditions);
	}

	public function deleteRoom($conditions){
		RoomManager::deleteRoom($conditions);
	}

	public function updateRoom($data){
		$conditions['id'] = $data['id'];

		RoomManager::updateRoom($conditions,$data);
	}

	/**
	 * 组成数据
	 */
	private function formatData($data){
		$data['hotel_id'] = Auth::user()->id;

		return $data;
	}

	/**
	 * 生成二维码
	 *
	 * @param      string  $hotelId  The hotel identifier
	 * @param      string  $roomId   The room identifier
	 *
	 * @return     array   ( description_of_the_return_value )
	 */
	private function generateQRCode($hotelId,$roomId){

		$qrcodeParam = 'hotel_id='.$hotelId.'&room_id='.$roomId;

		$qrcodeName = time().$hotelId.$roomId;

		$qrCodeUri = public_path().'/qrcodes/'.$qrcodeName.'.png';

		\QrCode::format('png')->size(100)->generate($qrcodeParam,$qrCodeUri);

		return '/qrcodes/'.$qrcodeName.'.png';
	}
}